package com.gitee.fsmxm.thinking.in.spring.dependency.injection;

import com.gitee.fsmxm.thinking.in.spring.dependency.domain.UserHolder;
import com.gitee.fsmxm.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * 注解方式 依赖注入 demo
 */
public class AnnotationDependencyMethodInjectionDemo {

    // 静态字段 可以采用方法注入
    static UserHolder userHolder;

    UserHolder userHolder2;

    @Autowired
    public void initUserHolder(UserHolder userHolder) {
        this.userHolder = userHolder;
    }

    @Resource
    public void initUserHolder2(UserHolder userHolder) {
        this.userHolder2 = userHolder;
    }

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        applicationContext.register(AnnotationDependencyMethodInjectionDemo.class);

        BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        beanDefinitionReader.loadBeanDefinitions("classpath:/META-INF/dependency-lookup-context.xml");

        applicationContext.refresh();

        AnnotationDependencyMethodInjectionDemo bean = applicationContext.getBean(AnnotationDependencyMethodInjectionDemo.class);

        System.out.println(applicationContext.getBean(UserHolder.class) == bean.userHolder);
        System.out.println(applicationContext.getBean(UserHolder.class) == bean.userHolder2);

    }

    @Bean
    public UserHolder userHolder(User user) {
        // or new and use setter
        return new UserHolder(user);
    }

}
